<style lang="scss" scoped>
.header-search {
  font-size: 0 !important;

  .search-icon {
    cursor: pointer;
    font-size: 18px;
    vertical-align: middle;
  }

  .header-search-select {
    font-size: 18px;
    transition: width 0.2s;
    width: 0;
    overflow: hidden;
    background: transparent;
    border-radius: 0;
    display: inline-block;
    vertical-align: middle;

    ::v-deep {
      .el-input__inner {
        border-radius: 0;
        border: 0;
        padding-left: 0;
        padding-right: 0;
        box-shadow: none !important;
        border: none!important;
        vertical-align: middle;
      }
    }
  }

  &.show {
    .header-search-select {
      width: 210px;
      margin-left: 10px;
    }
  }
}
</style>

<template>
  <div :class="{'show':show}" class="header-search">
    <svg-icon class-name="search-icon" icon-class="search" class="search-icon"
    style="color: #686B73;font-size: 18px;position: relative;top: 6px;margin-right: 15px"
    @click.native.stop="click" />

    <el-select
      ref="headerSearchSelect"
      v-model="search"
      :remote-method="searchRoutes"
      filterable
      default-first-option
      remote
      placeholder="搜索"
      class="header-search-select"
      @change="change"
    >
      <!--      最开始版本-->
      <el-option v-for="option in options"
                 :key="option.id" :value="option"
                 :label="option.name">
      </el-option>
    </el-select>
  </div>
</template>

<script>
  // fuse is a lightweight fuzzy-search module
  // make search results more in line with expectations
  //import Fuse from 'fuse.js/dist/fuse.min.js';
  //import path from 'path';
  import { treeselect } from '@/api/login.api';
  import cacheAjaxWrapper from '@/utils/cacheAjaxWrapper';
  import { deepClone,setNavIdtoPath } from '@/utils';
  import svgIcon from '@base/svg-icon'

  export default {
    name: 'HeaderSearch',
    components: {
      svgIcon,
    },
    data() {
      return {
        search: '',
        options: [],
        searchPool: [],
        show: false,
        fuse: undefined,
        routerList: [],
      };
    },
    computed: {
      routes() {
        return this.$store?.getters?.permission_routes;
      },
    },
    watch: {
      /*  searchPool(list) {
          this.initFuse(list);
        },*/
      show(value) {
        if (value) {
          document.body.addEventListener('click', this.close);
        } else {
          document.body.removeEventListener('click', this.close);
        }
      },
    },
    async mounted() {
      var self = this;
      //第一版本
      //this.searchPool = this.generateRoutes(this.routes);
      this.searchPool = await this.ajaxgetAllRouters();



      //扁平化 tree
      var routerList = [];
      this.tree2list(this.searchPool, routerList);
      routerList = routerList.filter(item => {
        //过滤到有孩纸的menu 只要最底层的menu
        return (item && item.children && item.children.length <= 0) || (!item.children);
      });
      this.routerList = routerList;


    },
    methods: {
      /**
       * @description: 获取所有的菜单
       * @params
       * @return routerlist <types/routerlist.ts:routerlist>
       */
      async ajaxgetAllRouters() {
        var routerlist = await cacheAjaxWrapper('alltreeRouterList', () => treeselect(-1).then(res => res.data));
        return routerlist;
      },

      click() {
        this.show = !this.show;
        if (this.show) {
          this.$refs.headerSearchSelect && this.$refs.headerSearchSelect.focus();
        }
      },
      close() {
        this.$refs.headerSearchSelect && this.$refs.headerSearchSelect.blur();
        this.options = [];
        this.show = false;
      },
      /**
       * @description: 点击菜单之后
       * @params .val  菜的对象<types/routerlist.ts:routerItem>
       * @return
       */
      change(val) {
        const path = val.funUrl;
        /*    if (this.ishttp(val.funUrl)) {
              // http(s):// 路径新窗口打开
              const pindex = path && path.indexOf('http');
              window.open(path.substr(pindex, path.length), '_blank');
            } else {*/
        var _tempFullPath=setNavIdtoPath(val.funUrl,val.id)
        this.search = '';
        this.options = [];
        this.$nextTick(() => {
          this.show = false;
        });
        var _params=deepClone(val)
var _array=_params?.name?.split('->');
        _params.name=_array?.[(_array.length-1)||0]||''
        debugger
        this.$emit('selectMenu',_params/*menu*/)
      },
      initFuse(list) {
        this.fuse = new Fuse(list, {
          shouldSort: true,
          threshold: 0.4,
          location: 0,
          distance: 100,
          maxPatternLength: 32,
          minMatchCharLength: 1,
          keys: [{
            name: 'title',
            weight: 0.7,
          }, {
            name: 'path',
            weight: 0.3,
          }],
        });
      },
      // Filter out the routes that can be displayed in the sidebar
      // And generate the internationalized title
      generateRoutes(routes, basePath = '/', prefixTitle = []) {
        let res = [];

        for (const router of routes) {
          // skip hidden router
          if (router.hidden) {
            continue;
          }

          const data = {
            path: !this.ishttp(router.path) ? path.resolve(basePath, router.path) : router.path,
            title: [...prefixTitle],
          };

          if (router.meta && router.meta.title) {
            data.title = [...data.title, router.meta.title];

            if (router.redirect !== 'noRedirect') {
              // only push the routes with title
              // special case: need to exclude parent router without redirect
              res.push(data);
            }
          }

          // recursive child routes
          if (router.children) {
            const tempRoutes = this.generateRoutes(router.children, data.path, data.title);
            if (tempRoutes.length >= 1) {
              res = [...res, ...tempRoutes];
            }
          }
        }
        return res;
      },
      querySearch(query) {
        if (query !== '') {
          this.options = this.fuse.search(query);
        } else {
          this.options = [];
        }
      },
      //递归
      tree2list(tree = [], list = [], parentNode = {}) {
        for (let i = 0; i < tree.length; i++) {
          var oneNode = tree[i];
          if (oneNode.funType === 3) {
            continue;
          }
          if (oneNode) {
            var parentName = parentNode && parentNode.name;
            if (parentName) {
              oneNode.name = parentName + '->' + oneNode.name;
            }
            list.push(oneNode);
          }
          if (tree[i] && tree[i].children && tree[i].children.length > 0) {
            this.tree2list(tree[i].children, list, oneNode);
          }
        }
        return list;
      },
      searchRoutes(queryStr) {
        var tree = deepClone(this.searchPool);
        /* var routerList = [];
         // debugger
         // console.log('this.$store.state.permisions.sidebarRouters', this.$store.state.permission.sidebarRouters);
         this.tree2list(tree, routerList);
         routerList = routerList.filter(item => {
           //过滤到有孩纸的menu 只要最底层的menu
           return (item && item.children && item.children.length <= 0) || (!item.children);
         });*/
        var searchList = this.routerList.filter(item => item && item.name.indexOf(queryStr) >= 0);
        console.log('searchList', searchList);
        this.options = searchList;
        return searchList;
      },

      ishttp(url) {
        return url && url.indexOf('http://') !== -1 || url && url.indexOf('https://') !== -1;
      },
    },
  };
</script>

<style lang="scss" scoped>
  .header-search {
    font-size: 0 !important;

    .search-icon {
      cursor: pointer;
      font-size: 18px;
      vertical-align: middle;
    }

    .header-search-select {
      font-size: 18px;
      transition: width 0.2s;
      width: 0;
      overflow: hidden;
      background: transparent;
      border-radius: 0;
      display: inline-block;
      vertical-align: middle;

      ::v-deep .el-input__inner {
        border-radius: 0;
        border: 0;
        padding-left: 0;
        padding-right: 0;
        box-shadow: none !important;
        border-bottom: 1px solid #d9d9d9;
        vertical-align: middle;
      }
    }

    &.show {
      .header-search-select {
        width: 210px;
        margin-left: 10px;
      }
    }
  }
</style>
